package ms.maplestory.boot.service.helpers;

import lombok.extern.slf4j.Slf4j;
import ms.maplestory.boot.client.character.Char;
import ms.maplestory.boot.client.character.Inventory.Inventory;
import ms.maplestory.boot.client.character.Inventory.Item;
import ms.maplestory.boot.enums.InventoryType;
import ms.maplestory.boot.loaders.ItemData;
import ms.maplestory.boot.loaders.container.ItemInfo;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

@Slf4j
public class InventoryHelper {

    public InventoryHelper() {

    }

    public static Inventory getInventoryByType(Char chr, InventoryType invType) {
        switch (invType) {
            case Equipped:
                return chr.getEquippedInventory();
            case Equip:
                return chr.getEquipInventory();
            case Use:
                return chr.getUseInventory();
            case Etc:
                return chr.getEtcInventory();
            case Setup:
                return chr.getSetupInventory();
            case Cash:
                return chr.getCashInventory();
            default:
                return null;
        }
    }

    public static Item getItemByItemIDAndStackable(Inventory inventory, int itemId) {
        ItemInfo ii = ItemData.getItemInfoByID(itemId);
        if (ii == null) {
            return getItemByItemID(inventory, itemId);
        }
        return inventory.getItems().stream()
                .filter(item -> item.getItemId() == itemId && item.getQuantity() < ii.getSlotMax())
                .findFirst()
                .orElse(null);
    }

    public static Item getItemByItemID(Inventory inventory, int itemId) {
        return inventory.getItems().stream().filter(item -> (item.getItemId() == itemId) && item.getQuantity() != 0).findFirst().orElse(null);
    }

    public static int getFirstOpenSlot(Inventory inventory) {
        int oldIndex = 0;
        sortItemsByPosition(inventory);
        for (Item item : inventory.getItems()) {
            if (item.getPosition() - oldIndex > 1) {
                break;
            }
            oldIndex = item.getPosition();
        }
        return oldIndex + 1;
    }

    public static void sortItemsByPosition(Inventory inventory) {
        List<Item> temp = new ArrayList<>(inventory.getItems());
        temp.sort(Comparator.comparingInt(Item::getPosition));
        inventory.getItems().clear();
        inventory.getItems().addAll(temp);
    }
}
